<template>
  <el-dialog v-model="dialogVisible" :title="title" width="80%" destroy-on-close class="group-select-dialog" @close="handleClose" :style="{ marginTop: '5vh' }">
    <div class="dialog-content">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <div class="search-row">
          <el-input v-model="searchKeyword" placeholder="搜索群组名称" clearable class="search-input">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="selectedTags" multiple placeholder="标签筛选" clearable class="search-input">
            <el-option v-for="tag in tagList" :key="tag.id" :label="tag.label_name" :value="tag.id" />
          </el-select>
          <div class="button-group">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 群组列表 -->
      <div class="card-section" v-loading="loading">
        <div class="group-cards-grid">
          <div v-for="group in groupList" :key="group.id" class="group-card" :class="{ selected: isSelected(group) }" @click="handleCardClick(group)">
            <!-- 多选模式下的选择框 -->
            <div v-if="multiple" class="card-checkbox">
              <el-checkbox :model-value="isSelected(group)" @change="(val) => handleCheckboxChange(group, val)" @click.stop />
            </div>

            <!-- 群组头像 -->
            <div class="card-avatar">
              <template v-if="group.groupUrlList && group.groupUrlList.length > 0">
                <div class="group-avatar" :class="'avatar-count-' + Math.min(group.groupUrlList.length, 9)">
                  <div v-for="(url, index) in group.groupUrlList" :key="index" class="group-avatar-item">
                    <img :src="url" :alt="'群成员' + (index + 1)" />
                  </div>
                </div>
              </template>
              <div v-else class="default-group-avatar">
                <div class="group-avatar avatar-count-1">
                  <div class="group-avatar-item">
                    <el-icon size="24"><UserFilled /></el-icon>
                  </div>
                </div>
              </div>
            </div>

            <!-- 群组信息 -->
            <div class="card-content">
              <div class="group-name" :title="group.name + (group.memberCount ? '(' + group.memberCount + '人)' : '')">
                <span class="name-text">{{ group.name }}</span>
                <span v-if="group.memberCount" class="member-count">({{ group.memberCount }}人)</span>
              </div>
              <div v-if="group.group_create_time" class="group-info">
                <span class="create-time">
                  {{ group.group_create_time }}
                </span>
              </div>

              <!-- 标签 -->
              <div v-if="group.labels && group.labels.length > 0" class="group-tags">
                <el-tag v-for="tag in group.labels.slice(0, 3)" :key="tag.id" size="small" class="group-tag">
                  {{ tag.label_name }}
                </el-tag>
                <el-tooltip
                  v-if="group.labels.length > 3"
                  :content="
                    group.labels
                      .slice(3)
                      .map((tag) => tag.label_name)
                      .join('、')
                  "
                  placement="top"
                >
                  <el-tag size="small" class="group-tag more-tag"> +{{ group.labels.length - 3 }} </el-tag>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && groupList.length === 0" class="empty-state">
          <el-empty description="暂无群组数据" />
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 25, 30]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'GroupSelectDialog'
});
</script>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { UserFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getGroupContactsPage } from '@/api/wechat';
import { getAllLabel, getCustomerLabel } from '@/api/userRate/label';

interface Tag {
  id: string;
  label_name: string;
}

interface Group {
  id: string;
  wx_id: string;
  name: string;
  avatar_url: string;
  memberCount: number;
  owner: string;
  createTime: string;
  labels: Tag[];
  groupUrlList?: string[];
}

interface ApiGroupResponse {
  wechat_account_id: string;
  group_member_count: number;
  group_create_time: string;
  group_name: string;
  id: string;
  groupUrlList: string[];
  labels?: Array<{
    account_type: string;
    id: number;
    label_name: string;
  }>;
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择群组'
  },
  selectedGroups: {
    type: Array as () => string[],
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);

// 状态变量
const loading = ref(false);
const searchKeyword = ref('');
const selectedTags = ref<string[]>([]);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const groupList = ref<Group[]>([]);
const wxId = ref(JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id);
const tempSelectedGroups = ref<Group[]>([]);
const tagList = ref<Tag[]>([]);

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

// 方法
const fetchGroups = async () => {
  loading.value = true;
  try {
    // 如果有标签筛选，使用标签接口
    if (selectedTags.value.length > 0) {
      const res = await getCustomerLabel({
        wxId: wxId.value,
        customerName: searchKeyword.value || undefined,
        labels: selectedTags.value.join(','),
        current: currentPage.value,
        size: pageSize.value,
        type: '2' // 2表示群聊
      });

      if (res.data && res.data.records) {
        groupList.value = res.data.records.map((group: any) => ({
          id: group.customer_id || group.wx_account,
          name: group.customerName || '未命名群组',
          avatar_url: '',
          memberCount: group.groupMemberCount || 0,
          group_create_time: group.group_create_time || '',
          owner: group.user_id || '',
          createTime: group.group_create_time || '',
          wx_id: group.customer_id,
          labels: (group.labels || []).map((tag: any) => ({
            id: String(tag.id),
            label_name: tag.label_name
          }))
        }));
        total.value = res.data.total || 0;
      }
    } else {
      // 没有标签筛选时，使用原有接口
      const res = await getGroupContactsPage({
        wxId: wxId.value,
        current: currentPage.value,
        size: pageSize.value,
        groupName: searchKeyword.value
      });

      // 转换数据格式
      const groups = (res.data.records || []).map((group: ApiGroupResponse) => ({
        id: group.id,
        name: group.group_name || '未命名群组',
        avatar_url: group.groupUrlList?.[0] || '',
        memberCount: group.group_member_count || 0,
        group_create_time: group.group_create_time || 0,
        owner: group.wechat_account_id || '',
        createTime: group.group_create_time,
        wx_id: group.id,
        labels: (group.labels || []).map((label) => ({
          id: String(label.id),
          label_name: label.label_name
        })),
        groupUrlList: group.groupUrlList || []
      }));

      groupList.value = groups;
      total.value = res.data.total || 0;
    }

    // 初始化临时选中数据
    if (props.selectedGroups.length > 0) {
      tempSelectedGroups.value = groupList.value.filter((g) => props.selectedGroups.includes(g.id));
    }
  } catch (error) {
    ElMessage.error('获取群组列表失败');
  } finally {
    loading.value = false;
  }
};

const handleReset = () => {
  searchKeyword.value = '';
  selectedTags.value = [];
  currentPage.value = 1;
  fetchGroups();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchGroups();
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchGroups();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchGroups();
};

const isSelected = (group: Group) => {
  return tempSelectedGroups.value.some((g) => g.id === group.id);
};

const handleCancel = () => {
  emit('cancel');
  dialogVisible.value = false;
};

const handleConfirm = () => {
  const selectedGroups = tempSelectedGroups.value.map((g) => ({
    id: g.id,
    wx_id: g.id, // 添加 wx_id 字段，使用 id 作为 wx_id
    name: g.name,
    avatar_url: g.avatar_url,
    memberCount: g.memberCount,
    owner: g.owner
  }));
  emit('confirm', selectedGroups);
  dialogVisible.value = false;
};

const handleClose = () => {
  searchKeyword.value = '';
  selectedTags.value = [];
  currentPage.value = 1;
};

// 获取标签列表
const fetchTagList = async () => {
  try {
    const res = await getAllLabel();
    if (res.data) {
      tagList.value = res.data;
    }
  } catch (error) {
    console.error('获取标签列表失败:', error);
  }
};

// 卡片相关方法
const handleCardClick = (group: Group) => {
  if (props.multiple) {
    // 多选模式：切换选中状态
    const index = tempSelectedGroups.value.findIndex((g) => g.id === group.id);
    if (index > -1) {
      tempSelectedGroups.value.splice(index, 1);
    } else {
      tempSelectedGroups.value.push(group);
    }
  } else {
    // 单选模式：直接设置选中
    tempSelectedGroups.value = [group];
  }
};

const handleCheckboxChange = (group: Group, checked: boolean) => {
  if (checked) {
    if (!tempSelectedGroups.value.some((g) => g.id === group.id)) {
      tempSelectedGroups.value.push(group);
    }
  } else {
    const index = tempSelectedGroups.value.findIndex((g) => g.id === group.id);
    if (index > -1) {
      tempSelectedGroups.value.splice(index, 1);
    }
  }
};

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      fetchTagList();
      fetchGroups();
    }
  }
);
</script>

<style lang="scss" scoped>
.group-select-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
    .el-dialog__header {
      margin: 0;
      padding: 20px 24px;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.dialog-content {
  .filter-section {
    margin-bottom: 16px;
    background: #f9fafb;
    padding: 12px;
    border-radius: 8px;

    .search-row {
      display: flex;
      gap: 12px;
      align-items: center;

      .search-input {
        flex: 1;
        min-width: 0; // 防止flex子项溢出

        :deep(.el-input__wrapper) {
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          background: #fff;

          &:hover,
          &:focus-within {
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
          }
        }
      }

      .button-group {
        display: flex;
        flex-shrink: 0;
      }
    }
  }

  .card-section {
    background: #fff;
    min-height: 400px;

    .group-cards-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
      padding: 8px;

      @media (max-width: 1400px) {
        grid-template-columns: repeat(4, 1fr);
      }

      @media (max-width: 1200px) {
        grid-template-columns: repeat(3, 1fr);
      }

      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }

      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }
    }

    .group-card {
      position: relative;
      background: #fff;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      min-height: 160px;

      &:hover {
        border-color: #3b82f6;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
        transform: translateY(-2px);
      }

      &.selected {
        border-color: #3b82f6;
        background: #eff6ff;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
      }

      .card-checkbox {
        position: absolute;
        top: 8px;
        right: 8px;
        z-index: 2;
      }

      .card-avatar {
        margin-bottom: 8px;

        .group-avatar {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          border: 1px solid #fff;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
          transition: transform 0.3s ease;
          display: grid;
          gap: 1px;
          overflow: hidden;
          padding: 2px;
          place-items: center;

          &:hover {
            transform: scale(1.03);
          }
          background: #f5f5f5;

          &.avatar-count-1 {
            grid-template-columns: 1fr;
            grid-template-rows: 1fr;
          }

          &.avatar-count-2 {
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: 1fr;
          }

          &.avatar-count-3 {
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(2, 1fr);

            .group-avatar-item {
              width: 100%;
              height: 100%;

              &:first-child {
                grid-column: 1 / -1;
                width: 50%;
                margin: 0 auto;
              }
            }
          }

          &.avatar-count-4 {
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(2, 1fr);
          }

          &.avatar-count-5 {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(2, 1fr);
            gap: 2px;

            .group-avatar-item {
              width: 100%;
              height: 100%;

              &:nth-child(1) {
                grid-column: 1 / 2;
                transform: translateX(50%);
              }
              &:nth-child(2) {
                grid-column: 2 / 3;
                transform: translateX(50%);
              }
              &:nth-child(3) {
                grid-column: 1 / 2;
              }
              &:nth-child(4) {
                grid-column: 2 / 3;
              }
              &:nth-child(5) {
                grid-column: 3 / 4;
              }
            }
          }

          &.avatar-count-6 {
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(2, 1fr);
            gap: 1px;
          }

          &.avatar-count-7 {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 2px;

            .group-avatar-item {
              width: 100%;
              height: 100%;

              &:nth-child(1) {
                grid-column: 2 / 3; // 第一行居中
              }
              &:nth-child(2) {
                grid-column: 1 / 2;
              }
              &:nth-child(3) {
                grid-column: 2 / 3;
              }
              &:nth-child(4) {
                grid-column: 3 / 4;
              }
              &:nth-child(5) {
                grid-column: 1 / 2;
              }
              &:nth-child(6) {
                grid-column: 2 / 3;
              }
              &:nth-child(7) {
                grid-column: 3 / 4;
              }
            }
          }

          &.avatar-count-8 {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);

            .group-avatar-item {
              width: 100%;
              height: 100%;

              &:nth-child(1) {
                grid-column: 1 / 2;
                transform: translateX(50%);
              }
              &:nth-child(2) {
                grid-column: 2 / 3;
                transform: translateX(50%);
              }
              &:nth-child(3) {
                grid-column: 1 / 2;
              }
              &:nth-child(4) {
                grid-column: 2 / 3;
              }
              &:nth-child(5) {
                grid-column: 3 / 4;
              }
              &:nth-child(6) {
                grid-column: 1 / 2;
              }
              &:nth-child(7) {
                grid-column: 2 / 3;
              }
              &:nth-child(8) {
                grid-column: 3 / 4;
              }
            }
          }

          &.avatar-count-9 {
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
          }

          .group-avatar-item {
            width: 100%;
            overflow: hidden;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }

        .default-group-avatar {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          background: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #999;
        }
      }

      .card-content {
        flex: 1;
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 4px;

        .group-name {
          font-size: 14px;
          font-weight: 600;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;

          .name-text {
            color: #1f2937;
          }

          .member-count {
            color: #6b7280;
            font-weight: 400;
            margin-left: 2px;
          }
        }

        .group-info {
          font-size: 12px;
          color: #6b7280;

          .create-time {
            font-size: 11px;
            opacity: 0.8;
          }
        }

        .group-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 2px;
          justify-content: center;
          margin-top: 4px;
          max-height: 40px;
          overflow: hidden;

          .group-tag {
            font-size: 10px;
            padding: 1px 4px;
            border-radius: 8px;
            background: #f3f4f6;
            border-color: #e5e7eb;
            color: #4b5563;
            border: 1px solid #e5e7eb;
            line-height: 1.2;

            &.more-tag {
              background: #e5e7eb;
              color: #6b7280;
              cursor: pointer;

              &:hover {
                background: #d1d5db;
              }
            }
          }
        }
      }
    }

    .empty-state {
      padding: 60px 20px;
      text-align: center;
    }
  }

  .pagination-container {
    padding: 12px;
    display: flex;
    justify-content: flex-end;
    background: #fff;
  }
}

// 优化按钮样式
:deep(.dialog-footer) {
  .el-button {
    padding: 8px 20px;
    font-weight: 500;
    border-radius: 6px;

    &--default {
      border-color: #e5e7eb;
      color: #4b5563;

      &:hover {
        border-color: #3b82f6;
        color: #3b82f6;
      }
    }

    &--primary {
      background: #3b82f6;
      border-color: #3b82f6;

      &:hover {
        background: #2563eb;
        border-color: #2563eb;
      }
    }
  }
}
</style>
